package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.mapper.QuotationDetailMapper;
import com.intelligent.pojo.Product;
import com.intelligent.pojo.QuotationDetail;
import com.intelligent.pojo.Unit;
import com.intelligent.service.ProductService;
import com.intelligent.service.QuotationDetailService;
import com.intelligent.service.UnitService;
import com.intelligent.vo.QuotationDetailPageReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 报价明细Service实现类
*/
@Service
public class QuotationDetailServiceImpl extends ServiceImpl<QuotationDetailMapper, QuotationDetail>
        implements QuotationDetailService {

    @Autowired
    private ProductService productService;

    @Autowired
    private UnitService unitService;

    @Override
    public Page<QuotationDetail> pageWithRelations(QuotationDetailPageReq quotationDetailPageReq) {
        Page<QuotationDetail> page = new Page<>(quotationDetailPageReq.getPageNum(), quotationDetailPageReq.getPageSize());
        LambdaQueryWrapper<QuotationDetail> wrapper = new LambdaQueryWrapper<>();

        // 构建查询条件
        if (quotationDetailPageReq.getQuotationId() != null) {
            wrapper.eq(QuotationDetail::getQuotationId, quotationDetailPageReq.getQuotationId());
        }


        wrapper.orderByDesc(QuotationDetail::getId);
        Page<QuotationDetail> result = this.page(page, wrapper);

        // 填充产品信息
        fillProductInfo(result);

        // 填充单位信息
        fillUnitInfo(result);

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QuotationDetail createQuotationDetail(QuotationDetail quotationDetail) {
        // 计算金额
        calculateAmounts(quotationDetail);

        // 设置创建时间
        quotationDetail.setCreateTime(new Date());
        quotationDetail.setUpdateTime(new Date());

        // 保存
        boolean saved = this.save(quotationDetail);
        if (!saved) {
            throw new RuntimeException("保存报价明细失败");
        }

        return quotationDetail;
    }

    @Override
    public QuotationDetail getQuotationDetailInfo(Long id) {
        QuotationDetail quotationDetail = this.getById(id);
        if (quotationDetail == null) {
            return null;
        }

        // 填充产品信息
        if (quotationDetail.getProductId() != null) {
            Product product = productService.getById(quotationDetail.getProductId());
            if (product != null) {
                quotationDetail.setSpecification(product.getSpecification());
            }
        }

        // 填充单位信息
        return quotationDetail;
    }

    @Override
    public List<QuotationDetail> getDetailsByQuotationId(Long quotationId) {
        LambdaQueryWrapper<QuotationDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuotationDetail::getQuotationId, quotationId);
        wrapper.orderByAsc(QuotationDetail::getId);
        return this.list(wrapper);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchCreateQuotationDetails(List<QuotationDetail> quotationDetails) {
        if (quotationDetails == null || quotationDetails.isEmpty()) {
            return true;
        }

        Date now = new Date();
        for (QuotationDetail detail : quotationDetails) {
            // 计算金额
            calculateAmounts(detail);
            // 设置时间
            detail.setCreateTime(now);
            detail.setUpdateTime(now);
        }

        return this.saveBatch(quotationDetails);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean generateDefaultDetailForQuotation(Long quotationId) {
        if (quotationId == null) {
            return false;
        }
        QuotationDetail detail = new QuotationDetail();
        detail.setQuotationId(quotationId);
        detail.setQuantity(0);
        detail.setUnitPrice(BigDecimal.ZERO);
        detail.setTotalPrice(BigDecimal.ZERO);
        detail.setDiscountRate(BigDecimal.ZERO);
        detail.setDiscountAmount(BigDecimal.ZERO);
        detail.setFinalPrice(BigDecimal.ZERO);
        detail.setCreateTime(new Date());
        detail.setUpdateTime(new Date());
        return this.save(detail);
    }


    private void calculateAmounts(QuotationDetail quotationDetail) {
        if (quotationDetail.getQuantity() != null && quotationDetail.getUnitPrice() != null) {
            // 计算小计金额
            BigDecimal totalPrice = quotationDetail.getUnitPrice().multiply(new BigDecimal(quotationDetail.getQuantity()));
            quotationDetail.setTotalPrice(totalPrice);

            // 计算折扣金额
            BigDecimal discountAmount = BigDecimal.ZERO;
            if (quotationDetail.getDiscountRate() != null && quotationDetail.getDiscountRate().compareTo(BigDecimal.ZERO) > 0) {
                discountAmount = totalPrice.multiply(quotationDetail.getDiscountRate()).divide(new BigDecimal(100));
            }
            quotationDetail.setDiscountAmount(discountAmount);

            // 计算最终金额
            BigDecimal finalPrice = totalPrice.subtract(discountAmount);
            quotationDetail.setFinalPrice(finalPrice);
        }
    }


    private void fillProductInfo(Page<QuotationDetail> result) {
        if (result.getRecords() == null || result.getRecords().isEmpty()) {
            return;
        }

        List<Long> productIds = result.getRecords().stream()
            .map(QuotationDetail::getProductId)
            .filter(productId -> productId != null)
            .distinct()
            .collect(Collectors.toList());

        if (!productIds.isEmpty()) {
            List<Product> products = productService.listByIds(productIds);
            Map<Long, Product> productMap = products.stream()
                .collect(Collectors.toMap(Product::getProductId, product -> product));

            result.getRecords().forEach(detail -> {
                if (detail.getProductId() != null) {
                    Product product = productMap.get(detail.getProductId());
                    if (product != null) {
                        detail.setSpecification(product.getSpecification());
                    }
                }
            });
        }
    }


    private void fillUnitInfo(Page<QuotationDetail> result) {
        if (result.getRecords() == null || result.getRecords().isEmpty()) {
            return;
        }

        List<Long> unitIds = result.getRecords().stream()
            .map(QuotationDetail::getUnitId)
            .filter(unitId -> unitId != null)
            .distinct()
            .collect(Collectors.toList());

        if (!unitIds.isEmpty()) {
            List<Unit> units = unitService.listByIds(unitIds);
            Map<Long, Unit> unitMap = units.stream()
                .collect(Collectors.toMap(Unit::getUnitId, unit -> unit));

            result.getRecords().forEach(detail -> {
                if (detail.getUnitId() != null) {
                    Unit unit = unitMap.get(detail.getUnitId());

                }
            });
        }
    }
}
